package com.kws.merchant.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.google.common.util.concurrent.AtomicDouble;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.config.util.DateTimeUtil;
import com.kws.common.core.domain.R;
import com.kws.common.core.enums.ModelOpType;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.core.sys.Ksys;
import com.kws.common.core.utils.KConstants;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.redis.service.RedisService;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.config.MinioAPI;
import com.kws.merchant.domain.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.*;
import com.kws.merchant.domain.vo.*;
import com.kws.merchant.mapper.MerchantMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.FileUtil;
import com.kws.merchant.util.TimeUtil;
import com.kws.system.api.RemoteUserService;
import com.kws.system.api.domain.SysUser;
import com.kws.system.api.enumDo.RedisConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * (Merchant)表服务实现类
 *
 * @author yxy
 * @since 2024-11-01 09:43:21
 */
@Service("merchantService")
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {

    @Autowired
    private GoodsViewService goodsViewService;
    @Autowired
    private TargetService targetService;
    private static final Logger logger = LoggerFactory.getLogger(MerchantServiceImpl.class);

    @Autowired
    private MinioAPI minioAPI;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ShopCartService shopCartService;
    @Autowired
    private AttentionService attentionService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderPayLogService orderPayLogService;

    private final static String SLASH = "/";

    private final static String FILE_NAME_PREFIX_SEPARATOR = "-";
    @Autowired
    private RemoteUserService remoteUserService;

    @Value("${minio.ENDPOINT}")
    private String minioUrl;

    @Override
    public boolean checkLoginCompany(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        Merchant sysCompanyMessage = baseMapper.selectOne(queryWrapper);
        if (null != sysCompanyMessage) {
            return true;
        }
        return false;
    }

    @Override
    public boolean createCompanyMessage(CreateCompanyMessageRq rq) {
        Long userId = SecurityUtils.getUserId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        Merchant sysCompanyMessage1 = baseMapper.selectOne(queryWrapper);
        if (null != sysCompanyMessage1) {
            new ServiceException("该用户已申请企业，请勿重新申请！");
        }
        Merchant sysCompanyMessage = new Merchant();
        sysCompanyMessage.setUserId(SecurityUtils.getUserId());
        sysCompanyMessage.setCommercialType(rq.getCommercialType());
        if (CollectionUtil.isNotEmpty(rq.getUserRoleList()) && rq.getUserRoleList().size() == 1) {
            String userRole = rq.getUserRoleList().get(0);
            sysCompanyMessage.setUserRole(userRole);
        } else if (CollectionUtil.isNotEmpty(rq.getUserRoleList())) {
            String userRole = rq.getUserRoleList().get(0);
            for (int i = 1; i < rq.getUserRoleList().size(); i++) {
                userRole = userRole + "," + rq.getUserRoleList().get(i);
            }
            sysCompanyMessage.setUserRole(userRole);
        }
        sysCompanyMessage.setContactPerson(rq.getContactPerson());
        sysCompanyMessage.setContactInformation(rq.getContactInformation());
        sysCompanyMessage.setCorporateName(rq.getCorporateName());
        sysCompanyMessage.setDocumentType(rq.getDocumentType());
        sysCompanyMessage.setDocumentNumber(rq.getDocumentNumber());
        sysCompanyMessage.setDocumentPicture1Url(rq.getDocumentPicture1Url());
        sysCompanyMessage.setDocumentPicture2Url(rq.getDocumentPicture2Url());
        sysCompanyMessage.setBusinessLicenseUrl(rq.getBusinessLicenseUrl());
        sysCompanyMessage.setMerchantCertificationType(rq.getMerchantCertificationType());
        sysCompanyMessage.setAptitudeCertificate1Url(rq.getAptitudeCertificate1Url());
        sysCompanyMessage.setAptitudeCertificate2Url(rq.getAptitudeCertificate2Url());
        sysCompanyMessage.setAptitudeCertificate3Url(rq.getAptitudeCertificate3Url());
        sysCompanyMessage.setCompanyName(rq.getCompanyName());
        sysCompanyMessage.setCompanyAddress(rq.getCompanyAddress());
        if (CollectionUtil.isNotEmpty(rq.getBusinessScopeList()) && rq.getBusinessScopeList().size() == 1) {
            String businessScope = rq.getBusinessScopeList().get(0);
            sysCompanyMessage.setBusinessScope(businessScope);
        } else if (CollectionUtil.isNotEmpty(rq.getBusinessScopeList())) {
            String businessScope = rq.getBusinessScopeList().get(0);
            for (int i = 1; i < rq.getBusinessScopeList().size(); i++) {
                businessScope = businessScope + "," + rq.getBusinessScopeList().get(i);
            }
            sysCompanyMessage.setBusinessScope(businessScope);
        }
        sysCompanyMessage.setRegistrationCertificateNumber(rq.getRegistrationCertificateNumber());
        sysCompanyMessage.setBankCardType(rq.getBankCardType());
        sysCompanyMessage.setAccountBankName(rq.getAccountBankName());
        sysCompanyMessage.setBankAccountNumber(rq.getBankAccountNumber());
        sysCompanyMessage.setCompanyAddressLat(rq.getCompanyAddressLat());
        sysCompanyMessage.setCompanyAddressLng(rq.getCompanyAddressLng());
        //提交状态为待审核
        sysCompanyMessage.setStatus(2);
        //账号状态为不可用
        sysCompanyMessage.setEnable("0");
        //创建用户
        sysCompanyMessage.setUserId(userId);
        sysCompanyMessage.setCreateUser(userId);
        Ksys.setBasicModelData(sysCompanyMessage, SecurityUtils.getStringUserId(), KConstants.DATA_ENABLE, ModelOpType.CREATE);
        int insert = baseMapper.insert(sysCompanyMessage);
        if (insert == 1) {
            return true;
        }
        return false;
    }

    @Override
    public String uploadCompanyFile(MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            String bucketName = MinioCommonBucket.HUATAI_PUB_BUCKET;
            String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
            minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
            logger.info("上传地址为:{}" + objectKey);
            return minioUrl + "/" + MinioCommonBucket.HUATAI_PUB_BUCKET + "/" + objectKey;
        } catch (Exception e) {
            logger.error("上传失败，", e);
            throw new ServiceException("上传失败，请重新上传");
        }
    }

    @Override
    public Merchant queryCompanyMessageByUserId(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        Merchant sysCompanyMessage = baseMapper.selectOne(queryWrapper);
        return sysCompanyMessage;
    }

    private String getObjectKey(Long fileSize, String fileName) {
        String date = DateTimeUtil.format(LocalDate.now(), "yyyyMMdd");

        StringBuilder objectKey = new StringBuilder(date);
        objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
        return objectKey.toString();
    }

    /**
     * 商家入驻审核
     *
     * @param checkVo
     * @return
     */
    @Override
    public boolean merchantCheck(CheckVo checkVo) {
        Long id = checkVo.getId();
        Long userId = SecurityUtils.getUserId();
        Merchant companyMessage = this.getById(id);
        if (ObjectUtils.isEmpty(companyMessage)) {
            throw new RuntimeException("没有查到改商家提交的入驻申请");
        }
        Integer status = checkVo.getStatus();
        String approvalOpinion = checkVo.getApprovalOpinion();
        companyMessage.setStatus(status);
        companyMessage.setApprovalOpinion(approvalOpinion);
        //审核通过，改变账号状态为正常
        if (status == 0) {
            companyMessage.setEnable("0");
            companyMessage.setUpdateUser(userId);
        }

        return this.updateById(companyMessage);
    }

    /**
     * 商家入驻信息分页
     *
     * @param merchantPagePo
     * @return
     */
    @Override
    public Page<Merchant> pageList(MerchantPagePo merchantPagePo) {
        Page<Merchant> page = new Page<>(merchantPagePo.getPageSize(), merchantPagePo.getTotalPage());
        LambdaQueryWrapper<Merchant> queryWrapper = Wrappers.<Merchant>lambdaQuery();
        String name = merchantPagePo.getName();//名称
        String status = merchantPagePo.getStatus();//状态
        String role = merchantPagePo.getRole();//入驻角色
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.eq(Merchant::getCompanyName, name);
        }
        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.eq(Merchant::getStatus, status);
        }
        if (StringUtils.isNotEmpty(role)) {
            queryWrapper.like(Merchant::getUserRole, role);
        }
        return this.page(page, queryWrapper);
    }


    @Override
    public Merchant getByUserId(Long userId) {
        return this.getOne(Wrappers.<Merchant>lambdaQuery().eq(Merchant::getUserId, userId));
    }

    /**
     * 商家信息修改
     *
     * @param merchant
     * @return
     */
    @Override
    public Object updateMerchant(Merchant merchant) {
        Long companyId = SecurityUtils.getCompanyId();
        merchant.setLogo(FileUtil.subFileName(merchant.getLogo()));
        merchant.setDocumentPicture1Url(FileUtil.subFileName(merchant.getDocumentPicture1Url()));
        merchant.setDocumentPicture2Url(FileUtil.subFileName(merchant.getDocumentPicture2Url()));
        merchant.setBusinessLicenseUrl(FileUtil.subFileName(merchant.getBusinessLicenseUrl()));
        merchant.setAptitudeCertificate1Url(FileUtil.subFileName(merchant.getAptitudeCertificate1Url()));
        merchant.setAptitudeCertificate2Url(FileUtil.subFileName(merchant.getAptitudeCertificate2Url()));
        merchant.setAptitudeCertificate3Url(FileUtil.subFileName(merchant.getAptitudeCertificate3Url()));
        //加入缓存
        redisService.setCacheObject(RedisConstant.COMPANY_MESSAGE.getCode() + companyId, merchant);

        return this.updateById(merchant);
    }


    /**
     * 修改商品浏览记录时间
     *
     * @return
     */
    @Override
    public boolean updateGoodsView(Long goodsViewId) {
        GoodsView goodsView = goodsViewService.getById(goodsViewId);
        Date createTime = goodsView.getCreateTime();
        Date date = new Date();
        long l = TimeUnit.MILLISECONDS.toSeconds(date.getTime() - createTime.getTime());
        goodsView.setViewTime(l);
        return goodsViewService.updateById(goodsView);
    }

    @Override
    public Merchant detail() {
        Long companyId = AuthUtil.getLoginUser().getSysUser().getCompanyId();
        Object cacheObject = redisService.getCacheObject(RedisConstant.COMPANY_MESSAGE.getCode() + companyId);
        Merchant merchant = null;
        if (ObjectUtils.isNotEmpty(cacheObject)) {
            merchant = JSON.parseObject(cacheObject.toString(), Merchant.class);
        }
        if (ObjectUtils.isEmpty(merchant)) {
            merchant = this.getById(companyId);
        }
        if (ObjectUtils.isEmpty(merchant)) {
            throw new RuntimeException("没有查询到该商户信息");
        }
        merchant.setLogo(FileUtil.fixFileName() + merchant.getLogo());
        merchant.setDocumentPicture1Url(FileUtil.fixFileName() + merchant.getDocumentPicture1Url());
        merchant.setDocumentPicture2Url(FileUtil.fixFileName() + merchant.getDocumentPicture2Url());
        merchant.setBusinessLicenseUrl(FileUtil.fixFileName() + merchant.getBusinessLicenseUrl());
        merchant.setAptitudeCertificate1Url(FileUtil.fixFileName() + merchant.getAptitudeCertificate1Url());
        merchant.setAptitudeCertificate2Url(FileUtil.fixFileName() + merchant.getAptitudeCertificate2Url());
        merchant.setAptitudeCertificate3Url(FileUtil.fixFileName() + merchant.getAptitudeCertificate3Url());
        return merchant;
    }

    @Override
    public Merchant detailById(Long id) {
        Object cacheObject = redisService.getCacheObject(RedisConstant.COMPANY_MESSAGE.getCode() + id);
        Merchant merchant = null;
        if (ObjectUtils.isNotEmpty(cacheObject)) {
            merchant = JSON.parseObject(cacheObject.toString(), Merchant.class);
        }
        if (ObjectUtils.isEmpty(merchant)) {
            merchant = this.getById(id);
        }
        if (ObjectUtils.isEmpty(merchant)) {
            throw new RuntimeException("没有查询到该商户信息");
        }
        merchant.setLogo(FileUtil.fixFileName() + merchant.getLogo());
        merchant.setDocumentPicture1Url(FileUtil.fixFileName() + merchant.getDocumentPicture1Url());
        merchant.setDocumentPicture2Url(FileUtil.fixFileName() + merchant.getDocumentPicture2Url());
        merchant.setBusinessLicenseUrl(FileUtil.fixFileName() + merchant.getBusinessLicenseUrl());
        merchant.setAptitudeCertificate1Url(FileUtil.fixFileName() + merchant.getAptitudeCertificate1Url());
        merchant.setAptitudeCertificate2Url(FileUtil.fixFileName() + merchant.getAptitudeCertificate2Url());
        merchant.setAptitudeCertificate3Url(FileUtil.fixFileName() + merchant.getAptitudeCertificate3Url());
        return merchant;
    }

    /**
     * 商家项目统计
     *
     * @return
     */
    @Override
    public ItemStatisticsVo itemStatistics(ItemStatisticsPo itemStatisticsPo) {
        Long userId = itemStatisticsPo.getUserId();
        R<SysUser> sysUserR = remoteUserService.getUserById(userId);
        if (R.FAIL==sysUserR.getCode()){
            throw new ServiceException(sysUserR.getMsg());
        }
        SysUser sysUser = sysUserR.getData();
        Long companyId = sysUser.getCompanyId();
        List<Long> cidList = itemStatisticsPo.getCidList();
        String sql=" and item_id in (";
        String collect = cidList.stream().map(Object::toString).collect(Collectors.joining(", "));
        sql+=collect;
        sql+=")";
        //查询商家项目
        /*List<Item> items = itemService.listByMerchantId(companyId);
        AtomicInteger atomicInteger = new AtomicInteger();
        AtomicDouble atomicDouble = new AtomicDouble();
        items.forEach(x -> {
            String orderNo = x.getOrderNo();
            if (StringUtils.isNotEmpty(orderNo)) {
                //根据订单编号查询订单
                List<Order> orderList = orderService.detailByOrderNo(orderNo);
                if (orderList.size() != 0) {
                    atomicInteger.getAndIncrement();
                    orderList.forEach(y -> {
                        atomicDouble.getAndAdd(y.getOrderPrice().doubleValue());
                    });
                }

            }
        });*/
        ItemStatisticsVo itemStatisticsVo=orderService.itemStatistics(companyId,sql);
        return itemStatisticsVo;
    }

    /**
     * 商家收支管理-实时概况
     *
     * @param incomePo
     * @return
     */
    @Override
    public RealTimeVo realTimeOverview(IncomePo incomePo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        Integer type = incomePo.getType();//0设备 1服务
        String startTime = incomePo.getStartTime();
        String endTime = incomePo.getEndTime();
        CurrentLastTime currentLastTime = TimeUtil.currentLastTime(-1);
        Integer timeType = incomePo.getTimeType();//时间类型0日 1月 2季 3年
        //时间段为空则优先时间类型
        LinkedList<Double> todayList = new LinkedList<>();
        LinkedList<Double> yesterdayList = new LinkedList<>();
        LinkedList<String> timeList = new LinkedList<>();
        Double now = 0.0;//现在支付金额
        Double ago = 0.0;//之前支付金额
        Double countVisitor = 0.0;//访客数
        Double countView = 0.0;//浏览量
        Double countPayOrder = 0.0;//支付买家数
        Double OrderCountMap = 0.0;//在途订单数-支付订单数
        String nowSql = " ";
        String agoSql = " ";
        String typeSql0 = " ";
        String typeSql1 = " ";
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            nowSql += " and YEAR(create_time)=" + currentLastTime.getCurrentYear();
            agoSql += " and YEAR(create_time)=" + currentLastTime.getLastYear();
            switch (timeType) {
                case 0:
                    nowSql += " and MONTH(create_time)=" + currentLastTime.getCurrentMonth();
                    nowSql += " and DAY(create_time)=" + currentLastTime.getCurrentDay();
                    agoSql += " and MONTH(create_time)=" + currentLastTime.getLastMonth();
                    agoSql += " and DAY(create_time)=" + currentLastTime.getLastDay();
                    now = orderService.countPayBySql(companyId, type, nowSql);//现在支付金额
                    ago = orderService.countPayBySql(companyId, type, agoSql);//之前支付金额
                    countVisitor = goodsViewService.countViewByPeopleSql(companyId, type, nowSql);//访客数
                    countView = goodsViewService.countViewBySql(companyId, type, nowSql);//浏览量
                    countPayOrder = orderService.countPayPeopleBySql(companyId, type, nowSql);//支付买家数
                    OrderCountMap = orderService.countPayOrderBySql(companyId, type, nowSql);//支付订单数
                    typeSql0 = nowSql;
                    typeSql1 = agoSql;
                    for (int i = 0; i <= 24; i += 3) {
                        nowSql = typeSql0;
                        agoSql = typeSql1;
                        int startHour = 0;
                        if (i != 0) {
                            startHour = i - 3;
                        }
                        nowSql += " and HOUR(create_time) BETWEEN " + startHour + " and " + i;
                        agoSql += " and HOUR(create_time) BETWEEN " + startHour + " and " + i;
                        //按年月日查询小时支付金额-当前
                        Double nowPayData = orderService.countPayBySql(companyId, type, nowSql);
                        //按年月日查询小时支付金额-之前
                        Double agoPayData = orderService.countPayBySql(companyId, type, agoSql);
                        todayList.add(nowPayData);
                        yesterdayList.add(agoPayData);
                        timeList.add(String.valueOf(i));
                    }
                    break;
                case 1:
                    nowSql += " and MONTH(create_time)=" + currentLastTime.getCurrentMonth();
                    agoSql += " and MONTH(create_time)=" + currentLastTime.getLastMonth();
                    now = orderService.countPayBySql(companyId, type, nowSql);//现在支付金额
                    ago = orderService.countPayBySql(companyId, type, agoSql);//之前支付金额
                    countVisitor = goodsViewService.countViewByPeopleSql(companyId, type, nowSql);//访客数
                    countView = goodsViewService.countViewBySql(companyId, type, nowSql);//浏览量
                    countPayOrder = orderService.countPayPeopleBySql(companyId, type, nowSql);//支付买家数
                    OrderCountMap = orderService.countPayOrderBySql(companyId, type, nowSql);//支付订单数
                    typeSql0 = nowSql;
                    typeSql1 = agoSql;
                    for (int i = 1; i <= currentLastTime.getCurrentMaxDays(); i++) {
                        nowSql = typeSql0;
                        agoSql = typeSql1;
                        nowSql += " and DAY(create_time)=" + i;
                        agoSql += " and DAY(create_time)=" + i;
                        //按年月日查询月支付金额-当前
                        Double nowPayData = orderService.countPayBySql(companyId, type, nowSql);
                        //按年月日查询月支付金额-之前
                        Double agoPayData = orderService.countPayBySql(companyId, type, agoSql);
                        todayList.add(nowPayData);
                        yesterdayList.add(agoPayData);
                        timeList.add(String.valueOf(i));
                    }
                    break;
                case 2:
                    now = orderService.countPayBySql(companyId, type, nowSql);//现在支付金额
                    ago = orderService.countPayBySql(companyId, type, agoSql);//之前支付金额
                    countVisitor = goodsViewService.countViewByPeopleSql(companyId, type, nowSql);//访客数
                    countView = goodsViewService.countViewBySql(companyId, type, nowSql);//浏览量
                    countPayOrder = orderService.countPayPeopleBySql(companyId, type, nowSql);//支付买家数
                    OrderCountMap = orderService.countPayOrderBySql(companyId, type, nowSql);//支付订单数
                    typeSql0 = nowSql;
                    typeSql1 = agoSql;
                    for (int i = 1; i <= 4; i++) {
                        nowSql = typeSql0;
                        agoSql = typeSql1;
                        int startMonth = (i - 1) * 3;
                        int endMonth = i * 3;
                        nowSql += " and MONTH(create_time) BETWEEN " + startMonth + " and " + endMonth;
                        agoSql += " and MONTH(create_time) BETWEEN " + startMonth + " and " + endMonth;
                        //按年月日查询季度支付金额-当前
                        Double nowPayData = orderService.countPayBySql(companyId, type, nowSql);
                        //按年月日查询季度支付金额-之前
                        Double agoPayData = orderService.countPayBySql(companyId, type, agoSql);
                        todayList.add(nowPayData);
                        yesterdayList.add(agoPayData);
                        timeList.add(String.valueOf(i));
                    }
                    break;
                case 3:
                    now = orderService.countPayBySql(companyId, type, nowSql);//现在支付金额
                    ago = orderService.countPayBySql(companyId, type, agoSql);//之前支付金额
                    countVisitor = goodsViewService.countViewByPeopleSql(companyId, type, nowSql);//访客数
                    countView = goodsViewService.countViewBySql(companyId, type, nowSql);//浏览量
                    countPayOrder = orderService.countPayPeopleBySql(companyId, type, nowSql);//支付买家数
                    OrderCountMap = orderService.countPayOrderBySql(companyId, type, nowSql);//支付订单数
                    typeSql0 = nowSql;
                    typeSql1 = agoSql;
                    for (int i = 1; i <= 12; i++) {
                        nowSql = typeSql0;
                        agoSql = typeSql1;
                        nowSql += " and MONTH(create_time)=" + i;
                        agoSql += " and MONTH(create_time)=" + i;
                        //按年月日查询季度支付金额-当前
                        Double nowPayData = orderService.countPayBySql(companyId, type, nowSql);
                        //按年月日查询季度支付金额-之前
                        Double agoPayData = orderService.countPayBySql(companyId, type, agoSql);
                        todayList.add(nowPayData);
                        yesterdayList.add(agoPayData);
                        timeList.add(String.valueOf(i));
                    }
            }
        } else {
            Calendar calendar = Calendar.getInstance();
            try {
                calendar.setTime(sdf.parse(startTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String sql = " and  DATE(create_time) BETWEEN '" + startTime + "' AND '" + endTime + "'";

            long days = getDay(sdf, startTime, endTime);
            now = orderService.countPayBySql(companyId, type, sql);//现在支付金额
            ago = orderService.countPayBySql(companyId, type, sql);//之前支付金额
            countVisitor = goodsViewService.countViewByPeopleSql(companyId, type, sql);//访客数
            countView = goodsViewService.countViewBySql(companyId, type, sql);//浏览量
            countPayOrder = orderService.countPayPeopleBySql(companyId, type, sql);//支付买家数
            OrderCountMap = orderService.countPayOrderBySql(companyId, type, sql);//支付订单数
            typeSql0 = nowSql;
            typeSql1 = agoSql;
            for (int i = 0; i <= days; i++) {
                nowSql = typeSql0;
                agoSql = typeSql1;
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1; // 因为从0开始计数
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                int lastYear = year - 1;
                nowSql += " and YEAR(create_time)=" + year;
                nowSql += " and MONTH(create_time)=" + month;
                nowSql += " and DAY(create_time)=" + day;
                agoSql += " and YEAR(create_time)=" + lastYear;
                agoSql += " and MONTH(create_time)=" + month;
                agoSql += " and DAY(create_time)=" + day;
                //按年月日查询季度支付金额-当前
                Double nowPayData = orderService.countPayBySql(companyId, type, nowSql);
                //按年月日查询季度支付金额-之前
                Double agoPayData = orderService.countPayBySql(companyId, type, agoSql);
                todayList.add(nowPayData);
                yesterdayList.add(agoPayData);
                timeList.add(year + "-" + month + "-" + day);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
        RealTimeVo realTimeVo = new RealTimeVo();
        realTimeVo.setTimeList(timeList);
        realTimeVo.setTodayList(todayList);
        realTimeVo.setYesterdayList(yesterdayList);
        realTimeVo.setNow(now);
        realTimeVo.setAgo(ago);
        realTimeVo.setCountVisitor(countVisitor);
        realTimeVo.setCountPayOrder(countPayOrder);
        realTimeVo.setCountView(countView);
        realTimeVo.setOrderCountMap(OrderCountMap);
        return realTimeVo;
    }

    private int getDay(SimpleDateFormat sdf, String startTime, String endTime) {
        Date beginDate;
        Date endDate;
        long day = 0;
        try {
            //字符串转日期
            beginDate = sdf.parse(startTime);
            endDate = sdf.parse(endTime);
            //计算结果
            day = (endDate.getTime() - beginDate.getTime()) / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Math.toIntExact(day);
    }

    /**
     * 商家收支管理-浏览看板
     *
     * @param incomePo
     * @return
     */
    @Override
    public FlowTimeVo flowOverview(IncomePo incomePo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        Integer type = incomePo.getType();//0设备 1服务
        String startTime = incomePo.getStartTime();
        String endTime = incomePo.getEndTime();
        CurrentLastTime currentLastTime = TimeUtil.currentLastTime(-1);
        Integer timeType = incomePo.getTimeType();//时间类型0日 1月 2季 3年
        Double flow = 0.0;//人均浏览量
        Double flowCompare = 0.0;//人均浏览量比较
        Double remain = 0.0;//平均停留时间
        Double remainCompare = 0.0;//平均停留时间比较
        LinkedList<Double> flowList = new LinkedList<>();//浏览
        LinkedList<Double> remainList = new LinkedList<>();//停留
        LinkedList<String> timeList = new LinkedList<>();//时间
        //这里统一查询当月和上月
        //这个月的浏览量时间
        Double thisGoodsViewTime = goodsViewService.countTimeByYearAndMonth(companyId, currentLastTime.getCurrentYear(), currentLastTime.getCurrentMonth(), type);
        //上个月的浏览量时间
        Double lastGoodsViewTime = goodsViewService.countTimeByYearAndMonth(companyId, currentLastTime.getCurrentYear(), currentLastTime.getCurrentMonth(), type);
        //这个月的浏览量人数
        Double thisCountPeople = goodsViewService.countPeopleByYearAndMonth(companyId, currentLastTime.getLastYear(), currentLastTime.getLastMonth(), type);
        //上个月的浏览量人数
        Double lastCountPeople = goodsViewService.countPeopleByYearAndMonth(companyId, currentLastTime.getLastYear(), currentLastTime.getLastMonth(), type);
        //这个月浏览量
        Double thisCountView = goodsViewService.countViewTimeByYearAndMonth(companyId, currentLastTime.getLastYear(), currentLastTime.getLastMonth(), type);
        //上个月浏览量
        Double laseCountView = goodsViewService.countViewTimeByYearAndMonth(companyId, currentLastTime.getLastYear(), currentLastTime.getLastMonth(), type);
        flow = thisCountView / thisCountPeople;
        flowCompare = (thisCountView / thisCountPeople - laseCountView / lastCountPeople) / (laseCountView / lastCountPeople) / 100;
        remain = thisGoodsViewTime / thisCountPeople;
        remainCompare = (thisGoodsViewTime / thisCountPeople - lastGoodsViewTime / lastCountPeople) / (lastGoodsViewTime / lastCountPeople) / 100;
        if (Double.isNaN(flowCompare)) {
            flowCompare = 0.0;
        }
        if (Double.isNaN(remainCompare)) {
            remainCompare = 0.0;
        }
        String sql = " ";
        String typeSql0 = " ";
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            sql += " and YEAR(create_time)=" + currentLastTime.getCurrentYear();
            switch (timeType) {
                case 0:
                    sql += " and MONTH(create_time)=" + currentLastTime.getCurrentMonth();
                    sql += " and DAY(create_time)=" + currentLastTime.getCurrentDay();
                    typeSql0 = sql;
                    for (int i = 0; i <= 24; i += 3) {
                        sql = typeSql0;
                        int startHour = 0;
                        if (i != 0) {
                            startHour = i - 3;
                        }
                        sql += " and HOUR(create_time) BETWEEN " + startHour + " and " + i;
                        //按年月日查询小时浏览量
                        Double viewData = goodsViewService.countViewBySql(companyId, type, sql);
                        //按年月日查询小时停留时间-浏览时间
                        Double viewTimeData = goodsViewService.countViewTimeBySql(companyId, type, sql);
                        flowList.add(viewData);
                        remainList.add(viewTimeData);
                        timeList.add(String.valueOf(i));
                    }
                    break;
                case 1:
                    sql += " and MONTH(create_time)=" + currentLastTime.getCurrentMonth();
                    typeSql0 = sql;
                    for (int i = 1; i <= currentLastTime.getCurrentMaxDays(); i++) {
                        sql = typeSql0;
                        sql += " and DAY(create_time)=" + i;
                        //按年月查询每日浏览量
                        Double viewData = goodsViewService.countViewBySql(companyId, type, sql);
                        //按年月查询每日停留时间-浏览时间
                        Double viewTimeData = goodsViewService.countViewTimeBySql(companyId, type, sql);
                        flowList.add(viewData);
                        remainList.add(viewTimeData);
                        timeList.add(String.valueOf(i));
                    }
                    break;
                case 2:
                    typeSql0 = sql;
                    for (int i = 1; i <= 4; i++) {
                        sql = typeSql0;
                        int startMonth = (i - 1) * 3;
                        int endMonth = i * 3;
                        sql += " and MONTH(create_time) BETWEEN " + startMonth + " and " + endMonth;
                        //按年查询每季度季浏览量
                        Double viewData = goodsViewService.countViewBySql(companyId, type, sql);
                        //按年查询每季度季停留时间-浏览时间
                        Double viewTimeData = goodsViewService.countViewTimeBySql(companyId, type, sql);
                        flowList.add(viewData);
                        remainList.add(viewTimeData);
                        timeList.add(String.valueOf(i));
                    }
                    break;
                case 3:
                    typeSql0 = sql;
                    for (int i = 1; i <= 12; i++) {
                        sql = typeSql0;
                        sql += " and MONTH(create_time)=" + i;
                        //按年查询每季度季浏览量
                        Double viewData = goodsViewService.countViewBySql(companyId, type, sql);
                        //按年查询每季度季停留时间-浏览时间
                        Double viewTimeData = goodsViewService.countViewTimeBySql(companyId, type, sql);
                        flowList.add(viewData);
                        remainList.add(viewTimeData);
                        timeList.add(String.valueOf(i));
                    }
            }
        } else {

            Calendar calendar = Calendar.getInstance();
            try {
                calendar.setTime(sdf.parse(startTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long days = getDay(sdf, startTime, endTime);
            typeSql0 = sql;
            for (int i = 0; i <= days; i++) {
                sql = typeSql0;
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1; // 因为从0开始计数
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                sql += " and YEAR(create_time)=" + year;
                sql += " and MONTH(create_time)=" + month;
                sql += " and DAY(create_time)=" + day;
                //按年查询每季度季浏览量
                Double viewData = goodsViewService.countViewBySql(companyId, type, sql);
                //按年查询每季度季停留时间-浏览时间
                Double viewTimeData = goodsViewService.countViewTimeBySql(companyId, type, sql);
                flowList.add(viewData);
                remainList.add(viewTimeData);
                timeList.add(year + "-" + month + "-" + day);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
        FlowTimeVo flowTimeVo = new FlowTimeVo();
        flowTimeVo.setFlow(flow);
        flowTimeVo.setFlowCompare(flowCompare);
        flowTimeVo.setFlowList(flowList);
        flowTimeVo.setRemain(remain);
        flowTimeVo.setRemainCompare(remainCompare);
        flowTimeVo.setRemainList(remainList);
        flowTimeVo.setTimeList(timeList);
        return flowTimeVo;
    }

    /**
     * 商家收支管理-整体看板
     *
     * @param incomePo
     * @return
     */
    @Override
    public AllTineVo allOverview(IncomePo incomePo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Integer type = incomePo.getType();//0设备 1服务
        String startTime = incomePo.getStartTime();
        String endTime = incomePo.getEndTime();
        Integer timeType = incomePo.getTimeType();//时间类型0日 1月 2季 3年
        CurrentLastTime currentLastTime = TimeUtil.currentLastTime(-1);
        Double payMoney = 0.0;//支付金额
        Double payMoneyCompare = 0.0;//支付金额比较
        Double view = 0.0;//访客数
        Double viewCompare = 0.0;//访客数比较
        Double refund = 0.0;//退款
        Double refundCompare = 0.0;//退款比较
        LinkedList<Double> payMoneyList = new LinkedList<>();//支付金额数据
        LinkedList<Double> viewList = new LinkedList<>();//访客数据
        LinkedList<Double> refundList = new LinkedList<>();//成功退款数据
        LinkedList<Integer> timeList = new LinkedList<>();//成功退款数据
        //这里统一查询当月和上月
        //当月支付金额
        Double thisCountPay = orderService.countPayByYearAndMonth(companyId, currentLastTime.getCurrentYear(), currentLastTime.getCurrentMonth(), type);
        //上月月支付金额
        Double lastCountPay = orderService.countPayByYearAndMonth(companyId, currentLastTime.getLastYear(), currentLastTime.getLastMonth(), type);
        //这个月的浏览量人数
        Double thisCountPeople = goodsViewService.countPeopleByYearAndMonth(companyId, currentLastTime.getCurrentYear(), currentLastTime.getCurrentMonth(), type);
        //上个月的浏览量人数
        Double lastCountPeople = goodsViewService.countPeopleByYearAndMonth(companyId, currentLastTime.getLastYear(), currentLastTime.getLastMonth(), type);
        //当月退款
        Double thisRefundPay = orderService.refundPayByYearAndMonth(companyId, currentLastTime.getCurrentYear(), currentLastTime.getCurrentMonth(), type);
        //上月退款金额
        Double lastRefundPay = orderService.refundPayByYearAndMonth(companyId, currentLastTime.getLastYear(), currentLastTime.getLastMonth(), type);
        payMoney = thisCountPay;
        payMoneyCompare = (thisCountPay - lastCountPay) / lastCountPay / 100;
        view = thisCountPeople;
        viewCompare = (thisCountPeople - lastCountPeople) / lastCountPeople / 100;
        refund = thisRefundPay;
        refundCompare = (thisRefundPay - lastRefundPay) / lastRefundPay / 100;
        if (Double.isNaN(payMoneyCompare)) {
            payMoneyCompare = 0.0;
        }
        if (Double.isNaN(viewCompare)) {
            viewCompare = 0.0;
        }
        if (Double.isNaN(refundCompare)) {
            refundCompare = 0.0;
        }
        String sql = " ";
        String typeSql0 = " ";
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            switch (timeType) {
                case 0:
                    sql += " and MONTH(create_time)=" + currentLastTime.getCurrentMonth();
                    sql += " and DAY(create_time)=" + currentLastTime.getCurrentDay();
                    typeSql0 = sql;
                    for (int i = 0; i <= 24; i += 3) {
                        sql = typeSql0;
                        int startHour = 0;
                        if (i != 0) {
                            startHour = i - 3;
                        }
                        sql += " and HOUR(create_time) BETWEEN " + startHour + " and " + i;
                        //按年月日查询小时支付金额
                        Double payData = orderService.countPayBySql(companyId, type, sql);
                        //按年月日查询小时退款金额
                        Double refundData = orderService.refundPayBySql(companyId, type, sql);
                        //按年月日查询小时访客数
                        Double viewTimeData = goodsViewService.countViewByPeopleSql(companyId, type, sql);
                        payMoneyList.add(payData);
                        viewList.add(refundData);
                        refundList.add(viewTimeData);
                        timeList.add(i);
                    }
                    break;
                case 1:
                    sql += " and MONTH(create_time)=" + currentLastTime.getCurrentMonth();
                    typeSql0 = sql;
                    for (int i = 1; i <= currentLastTime.getCurrentMaxDays(); i++) {
                        sql = typeSql0;
                        sql += " and DAY(create_time)=" + i;
                        //按年月日查询天支付金额
                        Double payData = orderService.countPayBySql(companyId, type, sql);
                        //按年月日查询天退款金额
                        Double refundData = orderService.refundPayBySql(companyId, type, sql);
                        //按年月日查询天访客数
                        Double viewTimeData = goodsViewService.countViewByPeopleSql(companyId, type, sql);
                        payMoneyList.add(payData);
                        viewList.add(refundData);
                        refundList.add(viewTimeData);
                        timeList.add(i);
                    }
                    break;
                case 2:
                    typeSql0 = sql;
                    for (int i = 1; i <= 4; i++) {
                        sql = typeSql0;
                        int startMonth = (i - 1) * 3;
                        int endMonth = i * 3;
                        sql += " and MONTH(create_time) BETWEEN " + startMonth + " and " + endMonth;
                        //按年月日查询季度支付金额
                        Double payData = orderService.countPayBySql(companyId, type, sql);
                        //按年月日查询季度退款金额
                        Double refundData = orderService.refundPayBySql(companyId, type, sql);
                        //按年月日查询季度访客数
                        Double viewTimeData = goodsViewService.countViewByPeopleSql(companyId, type, sql);
                        payMoneyList.add(payData);
                        viewList.add(refundData);
                        refundList.add(viewTimeData);
                        timeList.add(i);
                    }
                    break;
                case 3:
                    typeSql0 = sql;
                    for (int i = 1; i <= 12; i++) {
                        sql = typeSql0;
                        sql += " and MONTH(create_time)=" + i;
                        //按年月日查询月支付金额
                        Double payData = orderService.countPayBySql(companyId, type, sql);
                        //按年月日查询月退款金额
                        Double refundData = orderService.refundPayBySql(companyId, type, sql);
                        //按年月日查询月访客数
                        Double viewTimeData = goodsViewService.countViewByPeopleSql(companyId, type, sql);
                        payMoneyList.add(payData);
                        viewList.add(refundData);
                        refundList.add(viewTimeData);
                        timeList.add(i);
                    }
            }
        } else {
            Calendar calendar = Calendar.getInstance();
            try {
                calendar.setTime(sdf.parse(startTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long days = getDay(sdf, startTime, endTime);

            typeSql0 = sql;
            for (int i = 0; i <= days; i++) {
                sql = typeSql0;
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1; // 因为从0开始计数
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                sql += " and YEAR(create_time)=" + year;
                sql += " and MONTH(create_time)=" + month;
                sql += " and DAY(create_time)=" + day;
                //按年月日查询月支付金额
                Double payData = orderService.countPayBySql(companyId, type, sql);
                //按年月日查询月退款金额
                Double refundData = orderService.refundPayBySql(companyId, type, sql);
                //按年月日查询月访客数
                Double viewTimeData = goodsViewService.countViewByPeopleSql(companyId, type, sql);
                payMoneyList.add(payData);
                viewList.add(refundData);
                refundList.add(viewTimeData);
                timeList.add(i);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
        AllTineVo allTineVo = new AllTineVo();
        allTineVo.setPayMoney(payMoney);
        allTineVo.setPayMoneyCompare(payMoneyCompare);
        allTineVo.setPayMoneyList(payMoneyList);
        allTineVo.setRefund(refund);
        allTineVo.setRefundCompare(refundCompare);
        allTineVo.setRefundList(refundList);
        allTineVo.setView(view);
        allTineVo.setViewCompare(viewCompare);
        allTineVo.setViewList(viewList);
        allTineVo.setTimeList(timeList);
        return allTineVo;
    }


    @Override
    public Object addMerChant(Merchant merchant) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        merchant.setLogo(FileUtil.subFileName(merchant.getLogo()));
        merchant.setDocumentPicture1Url(FileUtil.subFileName(merchant.getDocumentPicture1Url()));
        merchant.setDocumentPicture2Url(FileUtil.subFileName(merchant.getDocumentPicture2Url()));
        merchant.setBusinessLicenseUrl(FileUtil.subFileName(merchant.getBusinessLicenseUrl()));
        merchant.setAptitudeCertificate1Url(FileUtil.subFileName(merchant.getAptitudeCertificate1Url()));
        merchant.setAptitudeCertificate2Url(FileUtil.subFileName(merchant.getAptitudeCertificate2Url()));
        merchant.setAptitudeCertificate3Url(FileUtil.subFileName(merchant.getAptitudeCertificate3Url()));
        //提交状态为待审核
        merchant.setStatus(2);
        //账号状态为不可用
        merchant.setEnable("0");
        //创建用户
        merchant.setUserId(sysUser.getUserId());
        return this.save(merchant);
    }


    /**
     * 商家数据统计-昨日
     *
     * @return
     */
    @Override
    public LinkedList<MerchantStatisticVo> statistics() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getCompanyId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = TimeUtil.getTime();//今天的日期
        String yesterday = sdf.format(TimeUtil.addDayByDate(-1));//昨天的日期
        //查询商家指标
        List<Target> targetList = targetService.getMerchantByList();
        LinkedList<MerchantStatisticVo> list = new LinkedList<>();
        targetList.forEach(x -> {
            switch (x.getTargetName()) {
                case "支付金额":
                case "总收入":
                    MerchantStatisticVo payMap = new MerchantStatisticVo();
                    payMap.setTitle(x.getTargetName());
                    //总的支付金额
                    Double countPayNum = orderService.countPayNum(userId);
                    //当天支付金额
                    Double todayPayNum = orderService.merchantPayMoneyByTime(userId, today);
                    //昨天支付金额
                    Double yesterdayPayNum = orderService.merchantPayMoneyByTime(userId, yesterday);
                    payMap.setValue(countPayNum);
                    payMap.setYesterdayValue(yesterdayPayNum);
                    payMap.setTodayValue(todayPayNum);
                    list.add(payMap);
                    break;
                case "访客数":
                    MerchantStatisticVo goodsViewMap = new MerchantStatisticVo();
                    goodsViewMap.setTitle(x.getTargetName());
                    //总访客
                    Double countVisitor = goodsViewService.countVisitor(userId);
                    //当天访客数
                    Double todayVisitorNum = goodsViewService.merchantVisitorByTime(userId, today);
                    //昨天访客数
                    Double yesterdayVisitorNum = goodsViewService.merchantVisitorByTime(userId, yesterday);
                    goodsViewMap.setValue(countVisitor);
                    goodsViewMap.setTodayValue(todayVisitorNum);
                    goodsViewMap.setYesterdayValue(yesterdayVisitorNum);
                    list.add(goodsViewMap);
                    break;
                case "浏览量":
                case "浏览商品数"://浏览商品数就是浏览量
                    MerchantStatisticVo viewMap = new MerchantStatisticVo();
                    viewMap.setTitle(x.getTargetName());
                    //总浏览量
                    Double countView = goodsViewService.countView(userId);
                    //当天浏览量
                    Double todayViewNum = goodsViewService.merchantViewByTime(userId, today);
                    //昨天浏览量
                    Double yesterdayViewNum = goodsViewService.merchantViewByTime(userId, yesterday);
                    viewMap.setValue(countView);
                    viewMap.setTodayValue(todayViewNum);
                    viewMap.setYesterdayValue(yesterdayViewNum);
                    list.add(viewMap);
                    break;
                case "加购人数":
                    MerchantStatisticVo ShopCartMap = new MerchantStatisticVo();
                    ShopCartMap.setTitle(x.getTargetName());
                    //总加购人数
                    Double countShopCart = shopCartService.countShopCartByUser(userId);
                    //当天加购人数
                    Double todayShopCart = shopCartService.merchantShopCartByUserAndTime(userId, today);
                    //昨天加购人数
                    Double yesterdayShopCart = shopCartService.merchantShopCartByUserAndTime(userId, yesterday);
                    ShopCartMap.setValue(countShopCart);
                    ShopCartMap.setTodayValue(todayShopCart);
                    ShopCartMap.setYesterdayValue(yesterdayShopCart);
                    list.add(ShopCartMap);
                    break;
                case "收藏商品数":
                    MerchantStatisticVo collectMap = new MerchantStatisticVo();
                    collectMap.setTitle(x.getTargetName());
                    //总商品收藏
                    Double countCollect = attentionService.countCollect(userId);
                    //当天商品收藏
                    Double todayCollect = attentionService.listCollectByTime(userId, today);
                    //昨天商品收藏
                    Double yesterdayCollect = attentionService.listCollectByTime(userId, yesterday);
                    collectMap.setValue(countCollect);
                    collectMap.setTodayValue(todayCollect);
                    collectMap.setYesterdayValue(yesterdayCollect);
                    list.add(collectMap);
                    break;
                case "收藏人数":
                    MerchantStatisticVo CollectPersonMap = new MerchantStatisticVo();
                    CollectPersonMap.setTitle(x.getTargetName());
                    //总收藏人数
                    Double countCollectPerson = attentionService.countCollectPerson(userId);
                    //当天收藏人数
                    Double todayCollectPerson = attentionService.listCollectPersonByTime(userId, today);
                    //昨天收藏人数
                    Double yesterdayCollectPerson = attentionService.listCollectPersonByTime(userId, yesterday);
                    CollectPersonMap.setTodayValue(todayCollectPerson);
                    CollectPersonMap.setYesterdayValue(yesterdayCollectPerson);
                    CollectPersonMap.setValue(countCollectPerson);
                    list.add(CollectPersonMap);
                    break;
                case "订单数":
                    MerchantStatisticVo orderMap = new MerchantStatisticVo();
                    orderMap.setTitle(x.getTargetName());
                    //总订单数
                    Double countOrder = orderService.countOrder(userId);
                    //今天订单
                    Double todayOrder = orderService.listOrderByTime(userId, today);
                    //昨天订单
                    Double yesterdayOrder = orderService.listOrderByTime(userId, yesterday);
                    orderMap.setValue(countOrder);
                    orderMap.setTodayValue(todayOrder);
                    orderMap.setYesterdayValue(yesterdayOrder);
                    list.add(orderMap);
                    break;
                case "支付买家数":
                    MerchantStatisticVo orderPayMap = new MerchantStatisticVo();
                    orderPayMap.setTitle(x.getTargetName());
                    //总支付买家数
                    Double countPayOrder = orderService.countPayOrder(userId);
                    //今天支付买家数
                    Double todayPayOrder = orderService.listOrderPayByTime(userId, today);
                    //昨天支付买家数
                    Double yesterdayPayOrder = orderService.listOrderPayByTime(userId, yesterday);
                    orderPayMap.setValue(countPayOrder);
                    orderPayMap.setTodayValue(todayPayOrder);
                    orderPayMap.setYesterdayValue(yesterdayPayOrder);
                    list.add(orderPayMap);
                    break;

                case "在途订单金额":
                    MerchantStatisticVo yesterdayIncomeMap = new MerchantStatisticVo();
                    yesterdayIncomeMap.setTitle(x.getTargetName());
                    //总在途订单金额
                    Double countIncomeCount = orderPayLogService.payCount(userId, 0);
                    //昨日在途订单金额
                    Double yesterdayIncomeCount = orderPayLogService.payCountByTime(userId, 0, yesterday);
                    //今日在途订单金额
                    Double todayIncomeCount = orderPayLogService.payCountByTime(userId, 0, today);
                    yesterdayIncomeMap.setValue(countIncomeCount);
                    yesterdayIncomeMap.setYesterdayValue(yesterdayIncomeCount);
                    yesterdayIncomeMap.setTodayValue(todayIncomeCount);
                    list.add(yesterdayIncomeMap);
                    break;
                case "总支出":
                    MerchantStatisticVo PayMap = new MerchantStatisticVo();
                    PayMap.setTitle(x.getTargetName());
                    //总用户退款金额
                    Double countPayCount = orderPayLogService.countPayCount(userId, 1);
                    //今日用户退款金额
                    Double todayPayCount = orderPayLogService.payCountByTime(userId, 1, today);
                    //昨日用户退款金额
                    Double yesterdayPayCount = orderPayLogService.payCountByTime(userId, 1, yesterday);
                    PayMap.setValue(countPayCount);
                    PayMap.setTodayValue(todayPayCount);
                    PayMap.setYesterdayValue(yesterdayPayCount);
                    list.add(PayMap);
                    break;
                case "在途订单数":
                    MerchantStatisticVo OrderCountMap = new MerchantStatisticVo();
                    OrderCountMap.setTitle(x.getTargetName());
                    //总在途订单数
                    Double countOrderCount = orderPayLogService.countOrderCount(userId, 0);
                    //今日在途订单数
                    Double todayOrderCount = orderPayLogService.yesterdayOrderCount(userId, 0, today);
                    //昨日在途订单数
                    Double yesterdayOrderCount = orderPayLogService.yesterdayOrderCount(userId, 0, yesterday);
                    OrderCountMap.setValue(countOrderCount);
                    OrderCountMap.setTodayValue(todayOrderCount);
                    OrderCountMap.setYesterdayValue(yesterdayOrderCount);
                    list.add(OrderCountMap);
                    break;
            }
        });
        return list;
    }

    /**
     * 商家收支管理-支付金额排行
     *
     * @return
     */
    @Override
    public OrderRankMerchantVo merchantOverview(IncomePo incomePo) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        Integer type = incomePo.getType();
        String date = TimeUtil.getTime();//当前日期
        String beforeDate = TimeUtil.addDayByStr(-30);//30天前日期
        OrderRankMerchantVo orderRankMerchantVo = new OrderRankMerchantVo();
        //当前商家排行
        Integer serial = orderService.merchantPayRankingByOne(companyId, date, beforeDate, type);
        //商家用户支付排行
        List<OrderRankVo> list = orderService.userPayRanking(companyId, date, beforeDate, type);
        orderRankMerchantVo.setSerial(serial);
        orderRankMerchantVo.setOrderRankVoList(list);
        return orderRankMerchantVo;
    }

    /**
     * 微电网--销售额统计
     *
     * @param microgridPo
     * @return
     */
    @Override
    public MicrogridVo microgridSale(MicrogridPo microgridPo) {
        Long userId = microgridPo.getUserId();
        R<SysUser> sysUserR = remoteUserService.getUserById(userId);
        if (R.FAIL==sysUserR.getCode()){
            throw new ServiceException(sysUserR.getMsg());
        }
        SysUser sysUser = sysUserR.getData();
        Long companyId = sysUser.getCompanyId();
        List<String> cidList = microgridPo.getCidList();
        Integer timeType = microgridPo.getTimeType();//时间类型0日 1月 3年
        Calendar calendar = Calendar.getInstance();
        String time = microgridPo.getTime();
        String year = "";
        String month = "";
        if (StringUtils.isEmpty(time)) {
            //没有选择时间默认当前时间
            calendar.setTime(new Date());
            year = String.valueOf(calendar.get(Calendar.YEAR));
            month = String.valueOf(calendar.get(Calendar.MONTH) + 1); // 因为从0开始计数
        } else {
            String[] timeArr = time.split("-");
            switch (timeArr.length) {
                case 1:
                    year = timeArr[0];
                    break;
                case 2:
                    year = timeArr[0];
                    month = timeArr[1];
                    calendar.set(Calendar.YEAR, Integer.valueOf(year));
                    calendar.set(Calendar.MONTH, Integer.valueOf(month));
            }
        }

        //获取当月天数
        int currentMaxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        LinkedList<Double> dataList = new LinkedList<>();//支付金额数据
        LinkedList<String> timeList = new LinkedList<>();//时间
        String sql = " and YEAR(create_time)=" + year;
        String collect = cidList.stream().collect(Collectors.joining(","));
        if (StringUtils.isNotEmpty(collect)) {
            sql += " and item_id in (" + collect + ") ";
        }
        MicrogridVo microgridVo = new MicrogridVo();
        String typeSql0 = " ";
        switch (timeType) {
            case 1:
                sql += " and MONTH(create_time)=" + month;
                typeSql0 = sql;
                for (int i = 1; i <= currentMaxDays; i++) {
                    sql = typeSql0;
                    sql += " and DAY(create_time)=" + i;
                    //按年月日查询天支付金额
                    Double payData = orderService.countPayBySql(companyId, null, sql);
                    dataList.add(payData);
                    timeList.add(String.valueOf(i));
                }
                break;
            case 2:
                typeSql0 = sql;
                for (int i = 1; i <= 12; i++) {
                    sql = typeSql0;
                    sql += " and MONTH(create_time)=" + i;
                    //按年月日查询月支付金额
                    Double payData = orderService.countPayBySql(companyId, null, sql);
                    dataList.add(payData);
                    timeList.add(String.valueOf(i));
                }
                break;
        }
        microgridVo.setTimeList(timeList);
        microgridVo.setDataList(dataList);
        return microgridVo;
    }

    /**
     * 微电网--销售额分类
     *
     * @param microgridPo
     * @return
     */
    @Override
    public List<MicrogridSale> microgridSaleType(MicrogridPo microgridPo) {
        Long userId = microgridPo.getUserId();
        R<SysUser> sysUserR = remoteUserService.getUserById(userId);
        if (R.FAIL==sysUserR.getCode()){
            throw new ServiceException(sysUserR.getMsg());
        }
        SysUser sysUser = sysUserR.getData();
        Long companyId = sysUser.getCompanyId();
        Integer timeType = microgridPo.getTimeType();//时间类型0日 1月 3年
        Calendar calendar = Calendar.getInstance();
        List<String> cidList = microgridPo.getCidList();
        String time = microgridPo.getTime();
        String year = "";
        String month = "";
        String day = "";
        if (StringUtils.isEmpty(time)) {
            //没有选择时间默认当前时间
            calendar.setTime(new Date());
            year = String.valueOf(calendar.get(Calendar.YEAR));
            month = String.valueOf(calendar.get(Calendar.MONTH) + 1); // 因为从0开始计数
            day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        } else {
            String[] timeArr = time.split("-");
            switch (timeArr.length) {
                case 1://年
                    year = timeArr[0];
                    break;
                case 2://月
                    year = timeArr[0];
                    month = timeArr[1];
                    break;
                case 3://日
                    year = timeArr[0];
                    month = timeArr[1];
                    day = timeArr[2];
                    break;
            }
        }
        String sql = " and YEAR(create_time)=" + year;
        String collect = cidList.stream().collect(Collectors.joining(","));
        if (StringUtils.isNotEmpty(collect)) {
            sql += " and item_id in (" + collect + ") ";
        }
        MicrogridVo microgridVo = new MicrogridVo();
        switch (timeType) {
            //时间类型0日 1月 3年
            case 0:
                sql += " and MONTH(create_time)=" + month;
                sql += " and DAY(create_time)=" + day;
                break;
            case 1:
                sql += " and MONTH(create_time)=" + month;
                break;
            case 2:
                break;
        }
        //按项目类型统计销售额
        List<MicrogridSale> microgridSale = orderService.countPayBySqlGroupByProjectType(companyId, sql);
        return microgridSale;
    }

    /**
     * 微电网--运维统计
     *
     * @param microgridOrderPo
     * @return
     */
    @Override
    public MicrogridVo microgridWorkOrder(MicrogridOrderPo microgridOrderPo) {
        Long userId = microgridOrderPo.getUserId();
        R<SysUser> sysUserR = remoteUserService.getUserById(userId);
        if (R.FAIL==sysUserR.getCode()){
            throw new ServiceException(sysUserR.getMsg());
        }
        SysUser sysUser = sysUserR.getData();
        Long companyId = sysUser.getCompanyId();
        Integer timeType = microgridOrderPo.getTimeType();//时间类型0日 1月 3年
        String time = microgridOrderPo.getTime();
        Integer workType = microgridOrderPo.getWorkType();//0工单 1巡检 2报修 3抢修
        List<String> cidList = microgridOrderPo.getCidList();
        Calendar calendar = Calendar.getInstance();
        String year = "";
        String month = "";
        String day = "";
        if (StringUtils.isEmpty(time)) {
            //没有选择时间默认当前时间
            calendar.setTime(new Date());
            year = String.valueOf(calendar.get(Calendar.YEAR));
            month = String.valueOf(calendar.get(Calendar.MONTH) + 1); // 因为从0开始计数
            day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        } else {
            String[] timeArr = time.split("-");
            switch (timeArr.length) {
                case 1://年
                    year = timeArr[0];
                    break;
                case 2://月
                    year = timeArr[0];
                    month = timeArr[1];
                    break;
                case 3://日
                    year = timeArr[0];
                    month = timeArr[1];
                    day = timeArr[2];
                    break;
            }
        }
        //获取当月天数
        int currentMaxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        LinkedList<Double> dataList = new LinkedList<>();//支付金额数据
        LinkedList<String> timeList = new LinkedList<>();//时间
        String sql = " and YEAR(create_time)=" + year;
        String collect = cidList.stream().collect(Collectors.joining(","));
        if (StringUtils.isNotEmpty(collect)) {
            sql += " and item_id in (" + collect + ") ";
        }
        MicrogridVo microgridVo = new MicrogridVo();
        String typeSql0 = " ";
        switch (timeType) {
            case 0:
                sql += " and MONTH(create_time)=" + year;
                sql += " and DAY(create_time)=" + month;
                typeSql0 = sql;
                for (int i = 0; i <= 24; i += 3) {
                    sql = typeSql0;
                    int startHour = 0;
                    if (i != 0) {
                        startHour = i - 3;
                    }
                    sql += " and HOUR(create_time) BETWEEN " + startHour + " and " + i;
                    //按年月日查询小时查询对应运维记录
                    Double payData = orderService.countWorkTypeBySql(companyId, workType, sql);
                    dataList.add(payData);
                    timeList.add(String.valueOf(i));
                }
                break;
            case 1:
                sql += " and MONTH(create_time)=" + month;
                typeSql0 = sql;
                for (int i = 1; i <= currentMaxDays; i++) {
                    sql = typeSql0;
                    sql += " and DAY(create_time)=" + i;
                    //按年月日查询对应运维记录
                    Double payData = orderService.countWorkTypeBySql(companyId, workType, sql);
                    dataList.add(payData);
                    timeList.add(String.valueOf(i));
                }
                break;
            case 2:
                typeSql0 = sql;
                for (int i = 1; i <= 12; i++) {
                    sql = typeSql0;
                    sql += " and MONTH(create_time)=" + i;
                    //按年月日查询对应运维记录
                    Double payData = orderService.countWorkTypeBySql(companyId, workType, sql);
                    dataList.add(payData);
                    timeList.add(String.valueOf(i));
                }
                break;
        }
        microgridVo.setTimeList(timeList);
        microgridVo.setDataList(dataList);
        return microgridVo;
    }

    /**
     * 商家用户下拉
     *
     * @return
     */
    @Override
    public List<SysUser> merchantUserList() {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        return this.getBaseMapper().merchantUserList(companyId);
    }

    /**
     * 微电网--订单总览
     * @param microgridPo
     * @return
     */
    @Override
    public List<OrderOverviewVo> orderOverview(MicrogridPo microgridPo) {
        Long userId = microgridPo.getUserId();
        R<SysUser> sysUserR = remoteUserService.getUserById(userId);
        if (R.FAIL==sysUserR.getCode()){
            throw new ServiceException(sysUserR.getMsg());
        }
        SysUser sysUser = sysUserR.getData();
        Long companyId = sysUser.getCompanyId();
        Integer timeType = microgridPo.getTimeType();//时间类型0日 1月 3年
        Calendar calendar = Calendar.getInstance();
        List<String> cidList = microgridPo.getCidList();
        String time = microgridPo.getTime();
        String year = "";
        String month = "";
        String day = "";
        if (StringUtils.isEmpty(time)) {
            //没有选择时间默认当前时间
            calendar.setTime(new Date());
            year = String.valueOf(calendar.get(Calendar.YEAR));
            month = String.valueOf(calendar.get(Calendar.MONTH) + 1); // 因为从0开始计数
            day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        } else {
            String[] timeArr = time.split("-");
            switch (timeArr.length) {
                case 1://年
                    year = timeArr[0];
                    break;
                case 2://月
                    year = timeArr[0];
                    month = timeArr[1];
                    break;
                case 3://日
                    year = timeArr[0];
                    month = timeArr[1];
                    day = timeArr[2];
                    break;
            }
        }
        String sql = " and YEAR(create_time)=" + year;
        String collect = cidList.stream().collect(Collectors.joining(","));
        if (StringUtils.isNotEmpty(collect)) {
            sql += " and item_id in (" + collect + ") ";
        }
        MicrogridVo microgridVo = new MicrogridVo();
        switch (timeType) {
            //时间类型0日 1月 3年
            case 0:
                sql += " and MONTH(create_time)=" + month;
                sql += " and DAY(create_time)=" + day;
                break;
            case 1:
                sql += " and MONTH(create_time)=" + month;
                break;
            case 2:
                break;
        }
        //按订单类型统计销售额
        List<MicrogridOrder> microgridSale = orderService.countPayBySqlGroupByOrderStatus(companyId, sql);
        //统计总的金额
        Integer orderCount=orderService.countOrderPrice(companyId,sql);
        ArrayList<OrderOverviewVo> orderOverviewVos = new ArrayList<>();
        microgridSale.forEach(x->{
            OrderOverviewVo orderOverviewVo = new OrderOverviewVo();
            BeanUtil.copyProperties(x,orderOverviewVo);
            Integer orderNum = orderOverviewVo.getOrderNum();
            if ((orderCount!=null||orderCount!=0)&&(orderNum!=null||orderNum!=0)){
                orderOverviewVo.setProportion(new BigDecimal(orderNum).divide(new BigDecimal(orderCount),2, RoundingMode.HALF_UP).doubleValue());
            }else{
                orderOverviewVo.setProportion(0.0);
            }
            orderOverviewVos.add(orderOverviewVo);
        });
        return orderOverviewVos;
    }
}
